# -*- coding: UTF-8 -*-
from sqlalchemy import *
from sqlalchemy.orm import *
from  sqlalchemy.ext.declarative import declarative_base

baseclass = declarative_base()
engine = create_engine('mysql://root:123456@127.0.0.1:3306/pymysqltest?charset=utf8')


class UserInfo(baseclass):
    __tablename__ = 'userinfo'
    uid = Column(Integer, Sequence('userid'), primary_key=True)
    name = Column(String(50))
    gender = Column(Boolean)


DBSession = sessionmaker(bind=engine)

class GetDbSession(object):
    def __init__(self):
        self.session=DBSession()

    def __enter__(self):
        return self.session

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is not None:
            self.session.rollback()
        self.session.close()


if __name__ == '__main__':
    baseclass.metadata.create_all(engine)
    with GetDbSession() as session:
        new_user = UserInfo(name=u'李四', gender=True)
        session.add(new_user)
        session.commit()
